package de.tum.in.elitese.wahlsys.common;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import sun.misc.BASE64Encoder;

/**
 * Helper Class for all digests of the Application
 * 
 * @author Christoph Frenzel
 */
public class DigestHelper {
	private static DigestHelper fInstance;

	static {
		fInstance = new DigestHelper();
	}

	/**
	 * @return Singleton
	 */
	public static DigestHelper getInstance() {
		return fInstance;
	}

	private BASE64Encoder fEncoder;

	private MessageDigest fMessageDigest;

	/**
	 * Constructor.
	 * 
	 * @throws KnownExecption
	 */
	private DigestHelper() throws KnownExecption {
		try {
			// get Digest
			fMessageDigest = MessageDigest.getInstance("SHA-256");
		} catch (NoSuchAlgorithmException e) {
			throw new KnownExecption("Fehler beim Initialisieren der Security Komponente.", e);
		}

		fEncoder = new BASE64Encoder();
	}

	/**
	 * Computes the digest for the given String.
	 * 
	 * @param string
	 * @return the digest as a String
	 */
	public String getDigestForString(String string) {
		byte[] bytes = fMessageDigest.digest(string.getBytes());

		return fEncoder.encode(bytes);
	}
}
